/*
 * 版权所有 (C) 2001-2014 深圳市艾派应用系统有限公司。保留所有权利。
 * 版本：
 * 修改记录：
 *      1、2014-11-21，tfl创建。 
 */
package com.chinamobile.ln.ictenterprises.http;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import com.chinamobile.ln.ictenterprises.utils.ValidateUtil;

import android.util.Log;

/**
 * HttpURLConnection工具类 ，默认UTF-8编码，以及请求方式为POST
 */
public class HttpTools
{

    private static final String TAG = "HttpTools";
    private static final String DEFAUL_ENCODE = "UTF-8";
    private static final String DEFAUL_METHOD = "POST";
    private static final int DEFAUL_TIMEOUTMILLIS = 10000;
    private static final int DEFAUL_READTIMEOUT = 10000;

    /**
     * 通过HttpURLConnection 请求服务器，返回字符串数据
     * @param requestUrl 地址
     * @param paramsMap 参数
     * @return
     */
    public static String doPostToServer(String requestUrl,
        Map<String, String> paramsMap)
    {
        return doPostToServer(requestUrl, paramsMap, DEFAUL_ENCODE);
    }

    /**
     * 通过HttpURLConnection 请求服务器，返回字符串数据
     * @param requestUrl 地址
     * @param paramsMap 参数
     * @param encode 编码 UTF-8 、 GBK
     * @return
     */
    public static String doPostToServer(String requestUrl,
        Map<String, String> paramsMap, String encode)
    {
        URL url = null;
        HttpURLConnection conn = null;
        OutputStream os = null;
        BufferedReader rd = null;
        String response = null;
        try
        {
            url = new URL(requestUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(DEFAUL_TIMEOUTMILLIS);
            conn.setRequestMethod(DEFAUL_METHOD);
            conn.setReadTimeout(DEFAUL_READTIMEOUT); // 读取超时
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            StringBuffer paramsBuff = new StringBuffer();
            String params = "";
            if (ValidateUtil.isNotEmpty(paramsMap))
            {
                for (Map.Entry<String, String> map : paramsMap.entrySet())
                {
                    paramsBuff.append(map.getKey()).append("=")
                        .append(map.getValue()).append("&");
                }
                params = paramsBuff.toString().substring(0,
                    paramsBuff.length() - 1);
            }
            os = conn.getOutputStream();
            os.write(params.getBytes(encode));
            os.flush();

            rd = new BufferedReader(new InputStreamReader(
                conn.getInputStream(), DEFAUL_ENCODE), 10 * 1024);
            String ch = null;
            StringBuffer sb = new StringBuffer();
            while ((ch = rd.readLine()) != null)
            {
                sb.append(ch);
            }
            response = sb.toString();
        }
        catch (Exception e)
        {
            Log.e(TAG, "请求接口出错：" + e.getMessage());
        }
        finally
        {
            if (os != null)
            {
                try
                {
                    os.close();
                }
                catch (IOException e)
                {
                    Log.e(TAG, "请求接口出错：" + e.getMessage());
                }
            }
            if (rd != null)
            {
                try
                {
                    rd.close();
                }
                catch (IOException e)
                {
                    Log.e(TAG, "关闭接口出错：" + e.getMessage());
                }
            }
            if (conn != null)
            {
                conn.disconnect();
            }
        }
        return response;
    }

    /**
     * 通过HttpURLConnection 请求服务器，返回byte[]字节的数据
     * @param requestUrl 地址
     * @param paramsMap 参数
     * @return
     */
    public static byte[] sendHttpReqToServer(String requestUrl,
        Map<String, String> paramsMap)
    {
        return sendHttpReqToServer(requestUrl, paramsMap, DEFAUL_ENCODE);
    }

    /**
     * Json 格式参数 post 请求
     * @param httpUri
     * @param params
     * @return
     */
    public static String doHttpPostRequest(String httpUri, String params)
    {
        byte data[] = null;
        String dataStr = null;
        try
        {
            URL url = new URL(httpUri);
            URLConnection connection = url.openConnection();
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);
            OutputStreamWriter out = new OutputStreamWriter(
                connection.getOutputStream(), "UTF-8");
            out.write(params);
            out.flush();
            out.close();
            InputStream is = connection.getInputStream();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = is.read(buff, 0, 100)) > 0)
            {
                bos.write(buff, 0, rc);
            }
            data = bos.toByteArray();
            dataStr = new String(data, "UTF-8");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return dataStr;
    }

    /**
     * 通过HttpURLConnection 请求服务器，返回byte[]字节的数据
     * @param requestUrl 地址
     * @param paramsMap 参数
     * @param encode 编码 UTF-8 、 GBK
     * @return
     */
    public static byte[] sendHttpReqToServer(String requestUrl,
        Map<String, String> paramsMap, String encode)
    {

        URL url = null;
        HttpURLConnection conn = null;
        OutputStream os = null;
        BufferedReader rd = null;
        byte[] response = null;
        try
        {
            url = new URL(requestUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(DEFAUL_TIMEOUTMILLIS);
            conn.setRequestMethod(DEFAUL_METHOD);
            conn.setReadTimeout(DEFAUL_READTIMEOUT); // 读取超时
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            StringBuffer paramsBuff = new StringBuffer();
            String params = "";
            if (ValidateUtil.isNotEmpty(paramsMap))
            {
                for (Map.Entry<String, String> map : paramsMap.entrySet())
                {
                    paramsBuff.append(map.getKey()).append("=")
                        .append(map.getValue()).append("&");
                }
                params = paramsBuff.toString().substring(0,
                    paramsBuff.length() - 1);
            }
            os = conn.getOutputStream();
            os.write(params.getBytes(encode));
            os.flush();
            InputStream is = conn.getInputStream();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int rc = 0;
            while ((rc = is.read(buffer)) > 0)
            {
                bos.write(buffer, 0, rc);
            }
            response = bos.toByteArray();
        }
        catch (Exception e)
        {
            Log.e(TAG, "请求接口出错：" + e.getMessage());
        }
        finally
        {
            if (os != null)
            {
                try
                {
                    os.close();
                }
                catch (IOException e)
                {
                    Log.e(TAG, "请求接口出错：" + e.getMessage());
                }
            }
            if (rd != null)
            {
                try
                {
                    rd.close();
                }
                catch (IOException e)
                {
                    Log.e(TAG, "关闭接口出错：" + e.getMessage());
                }
            }
            if (conn != null)
            {
                conn.disconnect();
            }
        }
        return response;
    }
}
